package com.server.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.server.date.DateType;
import com.server.date.DateUtil;
import com.server.service.IPapersPackagingService;
import com.server.service.IUserAssignmentService;
import com.server.web.DataVector;
import com.server.web.RequestInput;

/**
 * 试卷
 * @author wufeng
 * @date 创建时间：2016年7月15日 上午10:36:38 
 */
@Service("PapersPackagingService")
public class PapersPackagingService implements IPapersPackagingService{
	private static String tableName = "education.exam";
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private CommonDataService commonDataService;
	@Autowired
	private IUserAssignmentService userAssignmentService;
	
	@Override
	public DataVector<Map<String, Object>> getList(String type,int state,String user,RequestInput requestInput){
		StringBuffer whereStr = new StringBuffer();
		if(type.equals("2")){
			 whereStr.append("creater").append("=").append("'").append(user).append("'");
		}
		if(type.equals("")){
			
		}
		if(whereStr.length() > 0){
			whereStr.append("and");
		}
		if(state != -1){
			whereStr.append(" state=").append("'").append(state).append("'");
		}
		String sortStr = "createTime desc";
		DataVector<Map<String, Object>> listData = commonDataService.getListData("education.v_exam", whereStr.toString(), sortStr, requestInput);
		return listData;
	}
	
	@Override
	public boolean update(String id, Map<String, Object> inputMap, String operater) {
		if(StringUtils.isEmpty(operater)){
			return false;
		}
		boolean isSucess = true;
		for(int i = 1; i <= 4;i++){
			String string="";
			if(i == 1){
				string = "单选题";
			}else if (i == 2) {
				string = "多选题";
			}else if(i == 3){
				string = "判断题";
			}else if(i==4) {
				string = "解答题";
			}
			Object object = inputMap.get("score"+i);
			if(!StringUtils.isEmpty(object)&&isSucess){
				String sql = "UPDATE  education.exam_rela_exam_res SET score = '"+object.toString()+"' WHERE type = '"+string+"' AND  exam_id = '"+id+"' ";
				try {
					int update = jdbcTemplate.update(sql);
					if(update < 0){
						isSucess = false;
					}
					
				} catch (Exception e) {
					isSucess = false;
				}
			}
		}
		Object object = inputMap.get("score");
		Object object2 = inputMap.get("allScore");
		if(!StringUtils.isEmpty(object)&&!StringUtils.isEmpty(object2)&&isSucess){
			String sql ="update education.exam set score ='"+object.toString()+"',sumScore = '"+object2.toString()+"' where id = '"+id+"'";
			try {
				int update = jdbcTemplate.update(sql);
				if(update < 1){
					isSucess = false;
				}
			} catch (Exception e) {
				isSucess = false;
			}
			
		}
		return isSucess;
	
	}
	
	@Override
	public Map<String, Object> getMap(String id) {
		Map<String, Object> map = commonDataService.getFormData("education.v_exam", "id", id, null, null);
		return map;
	}
	
	@Override
	public boolean delete(String id) {
		boolean isSuccess = true;
		String sql ="DELETE education.exam,education.exam_rela_exam_res FROM education.exam"
		+ " LEFT JOIN education.exam_rela_exam_res ON education.exam.id=education.exam_rela_exam_res.exam_id WHERE education.exam.id='"+id+"'";
		String sql2 = "select exam_res_id from education.exam_rela_exam_res where exam_id = '"+id+"' and valid=1";
		List<Map<String, Object>>  list = jdbcTemplate.queryForList(sql2);
		for (Map<String, Object> map : list) {
			Object obj = map.get("exam_res_id");
			if(!StringUtils.isEmpty(obj)){
				String exam_res_id = obj.toString();
				String sql3 = "update education.exam_res SET useCount = useCount-1 WHERE id = '"+exam_res_id+"'";
				try {
					int update = jdbcTemplate.update(sql3);
					if(update <= 0){
						isSuccess = false;
					}
				} catch (Exception e) {
					isSuccess =false;
				}
			}
		}
		try {
			int update = jdbcTemplate.update(sql);
			if(update <= 0){
				isSuccess = false;
			}
		} catch (Exception e) {
			isSuccess = false;
		}
		return isSuccess;
	}
	

	@Override
	public Map<String, Object> add(Map<String, Object> inputMap, String operator) {
		if(StringUtils.isEmpty(operator)){
			return new HashMap<String, Object>();
		}
		Map<String, Object> inputParamMap = new HashMap<String, Object>();
		inputParamMap.put("name", inputMap.get("name"));//VARCHAR
		inputParamMap.put("class_id", inputMap.get("class_id"));//VARCHAR
		inputParamMap.put("courseId", inputMap.get("courseId"));//VARCHAR
		inputParamMap.put("courseName", inputMap.get("courseName"));//VARCHAR
		inputParamMap.put("time", inputMap.get("time"));//VARCHAR
		inputParamMap.put("isAuto", inputMap.get("isAuto"));//VARCHAR
		inputParamMap.put("creater", operator);
		Map<String, Object> execute = new SimpleJdbcCall(jdbcTemplate).withCatalogName("education")
			.withProcedureName("P_EXAM_ADD")
			.declareParameters(
						new SqlParameter("name",java.sql.Types.VARCHAR),
						new SqlParameter("class_id",java.sql.Types.VARCHAR),
						new SqlParameter("courseId",java.sql.Types.VARCHAR),
						new SqlParameter("courseName",java.sql.Types.VARCHAR),
						new SqlParameter("time",java.sql.Types.VARCHAR),
						new SqlParameter("isAuto",java.sql.Types.VARCHAR),
						new SqlParameter("creater",java.sql.Types.VARCHAR),
						new SqlOutParameter("id",java.sql.Types.INTEGER)
			).execute(inputParamMap);
		return execute;	
	}
	@Override
	public boolean addTestQuestions(String paperId, String testId, String type,String creater){
		if(StringUtils.isEmpty(creater)){
			return false;
		}
		String sql = "Insert into education.exam_rela_exam_res (exam_id,exam_res_id,type,creater) "
				+ "values ('"+paperId+"','"+testId+"','"+type+"','"+creater+"')";
		String sql2 = "update education.exam_res set useCount = useCount+1 where id = '"+testId+"' and valid = 1";
		boolean isSuccess = true;
		try {
			 int update = jdbcTemplate.update(sql);
			 if(update <= 0){
				 isSuccess =false;
			 }
		} catch (Exception e) {
			isSuccess =false;
		}
		
		if(isSuccess){
			try {
				int update = jdbcTemplate.update(sql2);
				if (update < 0) {
					isSuccess = false;
				}
			} catch (Exception e) {
				isSuccess = false;
			}
		}
		return isSuccess;
	}
	
	@Override
	public boolean isRight(String id, String operator) {
		String sql = "select creater from "+tableName+" where id = '"+id+"' and valid = 1";
		String authorship = jdbcTemplate.queryForObject(sql, String.class);
		if(operator.equals(authorship)){
			return true;
		}
		return false;
	}

	@Override
	public DataVector<Map<String, Object>> getQuetionsList(String type,
			RequestInput requestInput) {
		String whereStr = "class_id = '"+type+"'";
		DataVector<Map<String, Object>> reDataVector = commonDataService.getListData("education.exam_res", whereStr, null, requestInput);
		return reDataVector;
	}

	@Override
	public Map<String, Object> paperMap(String paperId) {
		Map<String, Object> map = new HashMap<String, Object>();
		String sql1 = "SELECT COUNT(type) As sum,score FROM education.exam_rela_exam_res where exam_id ='"+paperId+"' and type = '单选题'";
		String sql2 = "SELECT COUNT(type) As sum,score FROM education.exam_rela_exam_res where exam_id ='"+paperId+"' and type = '多选题'";
		String sql3 = "SELECT COUNT(type) As sum,score FROM education.exam_rela_exam_res where exam_id ='"+paperId+"' and type = '判断题'";
		String sql4 = "SELECT COUNT(type) As sum,score FROM education.exam_rela_exam_res where exam_id ='"+paperId+"' and type = '解答题'";
		String sql = "select sumScore, score, isAuto from education.exam where id ='"+paperId+"'";
		try { 
			Map<String, Object> map1 = jdbcTemplate.queryForMap(sql1);
			Map<String, Object> map2 = jdbcTemplate.queryForMap(sql2);
			Map<String, Object> map3 = jdbcTemplate.queryForMap(sql3);
			Map<String, Object> map4 = jdbcTemplate.queryForMap(sql4);
			map = jdbcTemplate.queryForMap(sql);
			map.put("one", map1);
			map.put("much", map2);
			map.put("judge", map3);
			map.put("solution", map4);
		} catch (Exception e) { 
			return new HashMap<String, Object>();
		}
		return map;
	}
	@Override
	public List<Map<String, Object>> getQuestionIdList(String paperId){
		String sql = "select exam_res_id from education.exam_rela_exam_res where exam_id = '"+paperId+"'";
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		try {
			list = jdbcTemplate.queryForList(sql);
		} catch (Exception e) {
			return new ArrayList<Map<String,Object>>();
		}
		return list;
		
	}
	@Override
	public boolean updateState(String id, int state, String operator, Boolean isAudit) {
		boolean isSuccess = true;
		String sql = null;
		if (isAudit) {
			sql = "update %s set state=%s,auditor='%s',auditTime='%s' where id=%s";
		}else {
			sql = "update %s set state=%s,evaluator='%s',evalueTime='%s' where id=%s";
		}
		String dateStr = DateUtil.getDateStr(new Date(),DateType.YYYY_MM_DD_HH_mm_ss_SSS);
		try {
			int update = jdbcTemplate.update(String.format(sql, tableName,state,operator,dateStr,id));
			if(update <= 0){
				isSuccess = false;
			}
		} catch (Exception e) {
			isSuccess = false;
		}
		return isSuccess;
	}
	@Override
	public boolean deleteTest(String id,String testId){
		boolean isSuccess = true;
		String sql3 = "delete from education.exam_rela_exam_res where "
				+ "exam_id = '"+id+"' and exam_res_id = '"+testId+"'";
		//String sql = "update education.exam set sumScore = 0 where id ='"+id+"'";
		try {
			 int update = jdbcTemplate.update(sql3);
			// int update1 = jdbcTemplate.update(sql);
			 if(update < 0){
				 isSuccess =false;
			 }
		} catch (Exception e) {
			isSuccess =false;
		}
		return isSuccess;
	}
	
	@Override
	public Integer toEstimate(String ids,String operator){
		StringBuffer idsBuffer = new StringBuffer();
		String[] split = ids.split(",");
		for(String id : split){
			Boolean estimateAssi = userAssignmentService.estimateAssi(Integer.parseInt(id), 2, 1);
			if (estimateAssi) {
				if (idsBuffer.length() > 0) {
					idsBuffer.append(",");
				}
				idsBuffer.append(id);
			}
		}
		if (idsBuffer.length() <= 0) {
			return 0;
		}
		String dateStr = DateUtil.getDateStr(new Date(),DateType.YYYY_MM_DD_HH_mm_ss_SSS);
		String sql = "update %s set state=1,mender='%s',updateTime='%s' where id in('%s')";
		return jdbcTemplate.update(String.format(sql, tableName,operator,dateStr,idsBuffer.toString().replaceAll(",", "','")));
	}
	
	@Override
	public List<Map<String, Object>> list(String examId) {
		String sql ="select exam_res_id from education.exam_rela_exam_res where exam_id ='"+examId+"'";
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		try {
			list = jdbcTemplate.queryForList(sql);
		} catch (Exception e) {
			return new ArrayList<Map<String,Object>>();
		}
		return list;
	}
}
